import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
        state: {
            cartList: []
        },
        mutations: {
            addCount(state, payload) {
                payload.count += 1
            },
            addToCart(state, payload) {
                state.cartList.push(payload)
            }
        },
        actions: {
            addCart(context, payload) {
                return new Promise((resolve, reject) => {
                    let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)

                    if (oldProduct) {
                        // oldProduct.count += 1
                        context.commit('addCount', payload)
                        resolve('加入购物车成功')
                    } else {
                        payload.count = 1
                            // state.cartList.push(payload)
                        context.commit('addToCart', payload)
                        resolve('加入购物车成功')
                    }
                })

            }
        }
    },

)